import { toArray } from 'pub-bbx-utils';
import { fmt_address, fmt_datetime, fmt_date } from '@src/filter/fmt';
import i18n from '@src/locales'

import * as FormUtil from './util';
import { FieldManager } from './components';
import http from '@src/util/http';
import platform from '@src/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
const link_reg = /((((https?|ftp?):(?:\/\/)?)(?:[-;:&=+$]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-?+=&;:%!/@.\w_]*)#?(?:[-+=&;%!?/@.\w_]*))?)/g;

const FormView = {
  name: 'mform-view',
  props: {
    fields: {
      type: Array,
      default: () => []
    },
    value: {
      type: Object,
      default: () => ({})
    },
    /* 全部字段 */
    allFields: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      sectionState: {}
    };
  },

  methods: {
    // TODO :预览图片
    previewImage(event) {
      const element = event.target;
      const imgSrc = element.currentSrc;

      if (
        (!/\.(png|bmp|gif|jpg|jpeg|tiff|tif|jfif|ico|pcx|tga)$/i.test(imgSrc) &&
          !imgSrc) ||
        !element
      )
        return;

      const list = event.target.closest('.ql-editor');
      const images = Array.prototype.slice.call(list.querySelectorAll('img'));

      let currIndex = 0;
      const urls = images.map((item, index) => {
        if (item == element) currIndex = index;
        return item.getAttribute('src');
      });
      platform.imagePreview({
        imageDom: list,
        currIndex,
        urls
      });
    },
    toggleDisplay(id) {
      this.sectionState[id] = !this.sectionState[id];
    },
    /** 格式化值 */
    formatValue(field, value) {
      // 多选
      if (FormUtil.isMultiSelect(field)) {
        return toArray(value).join('，');
      }

      // 日期
      if (FormUtil.isDate(field)) {
        return fmt_date(value);
      }

      // 日期时间
      if (FormUtil.isDatetime(field)) {
        return fmt_datetime(value);
      }

      // 人员
      if (field.formType === 'user') {
        // 多选
        if (Array.isArray(value)) {
          return value.map(i => i.displayName || i.name).join(',');
        }

        return value && (value.displayName || value.name);
      }

      return value;
    },
    buildProduct(product) {
      const { value, displayName, formType } = product;

      const className = {
        'form-view-row-content': true
        // link: formType === 'product'
      };
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>
            {value &&
              value.map((item, index) => (
                <span>
                  {item.label}
                  {index < value.length - 1 && <i>，</i>}
                </span>
              ))}
          </div>
        </div>
      );
    },
    buildCustomer(customer) {
      const { value, displayName, formType, originalVal } = customer;

      const className = {
        'form-view-row-content': true
        // link: formType === 'customer'
      };
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>
            {value &&
              value.map((item, index) => (
                <span>
                  {item.label}
                  {index < value.length - 1 && <i>，</i>}
                </span>
              ))}
          </div>
        </div>
      );
    },
    buildCommonDom({ displayName, value, formType }) {
      const className = {
        'form-view-row-content': true,
        'form-view-textarea-preview': formType === 'textarea'
      };

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class={className}>{value}</div>
        </div>
      );
    },
    buildAddressDom(address) {
      const { value, displayName, originalVal } = address;
      const map = {
        address: originalVal,
        title: displayName
      };

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            <span>{value}</span>
            {value && <i class="iconfont "></i>}
          </div>
        </div>
      );
    },

    buildPhoneDom(lmPhone) {
      const { value, displayName } = lmPhone;
      const hasCallCenterModule = localStorage.getItem('call_center_module');
      const str =
        hasCallCenterModule == 1 && value ? (
          <el-tooltip content={i18n.t('common.base.dial')} placement="top">
            <i
              onClick={() => this.makePhoneCall(value, hasCallCenterModule)}
              v-if="hasCallCenterModule"
              class="iconfont icon-dianhua1"
              style="color: #55B7B4;padding-left: 5px;font-size: 16px;cursor:pointer;"
            ></i>
          </el-tooltip>
        ) : (
          ''
        );
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            <span>{value}</span>
            {str}
          </div>
        </div>
      );
    },

    async makePhoneCall(phone, hasCallCenterModule) {
      if (!phone || !hasCallCenterModule) return;
      try {
        const { code, message } = await http.post(
          '/api/callcenter/outside/callcenter/api/dialout',
          { phone, taskType: 'customer' },
          false
        );
        if (code !== 0)
          return this.$platform.notification({
            title: i18n.t('common.base.callFail'),
            message: message || '',
            type: 'error'
          });
      } catch (error) {
        console.error(error);
      }
    },

    buildTextarea({ displayName, value, formType }) {
      const newVal = value
        ? value.replace(link_reg, match => {
            return `<a href="javascript:;" url="${match}">${match}</a>`;
          })
        : '';

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            <span
              domPropsInnerHTML={newVal}
              class="form-view-textarea-content"
              onClick={e => {
                e.stopPropagation();
                const url = e.target.getAttribute('url');

                if (!url) return;
                if (!/http/gi.test(url))
                  return platform.alert(i18n.t('common.base.tip.confirmHttpProtocol'));

                platform.openLink(url);
              }}
            >
              {newVal}
            </span>
          </div>
        </div>
      );
    },
    buildInfoDom(info) {
      const value = info.value;
      return (
        <div class="form-view-row">
          <div class="form-view-row-content form-view-info-content">
            <div class="form-ql-editor ql-container">
              <div
                class="ql-editor"
                domPropsInnerHTML={value}
                onClick={e => this.previewImage(e)}
              ></div>
            </div>
          </div>
        </div>
      );
    },
    buildAutoGraph({ displayName, value }) {
      return (
        <div class="form-view-row">
          <label>{displayName}</label>
          <div class="form-view-row-content">
            {value && (
              <div class="form-view-autograph-content">
                <img src={value} />
              </div>
            )}
          </div>
        </div>
      );
    },
    buildRelatedTask({ displayName, value }) {
      if (Array.isArray(value) && value.length > 0) {
        const _renderContent = value.map((item, index) => {
          const taskId = item.taskId || '';
          const taskNo = item.taskNo || '';

          return (
            <span>
              <a
                href="javascript:;"
                class="link-text"
                style="margin: 0"
                onClick={() => {
                  // this.$platform.openTab({
                  //   id: `task_view_${taskId}`,
                  //   title: `工单${taskNo}`,
                  //   close: true,
                  //   url: `/task/view/${taskId}?noHistory=1`
                  // });
                  openAccurateTab({
                    type: PageRoutesTypeEnum.PageTaskView,
                    key: taskId,
                    titleKey: taskNo,
                    params: 'noHistory=1'
                  })
                }}
              >
                {taskNo}
              </a>
              {index < value.length - 1 && ','}
            </span>
          );
        });

        return (
          <div class="form-view-row">
            <label>{displayName}</label>
            <div class="form-view-row-content">{_renderContent}</div>
          </div>
        );
      }

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
        </div>
      );
    },

    // 关联出入库
    buildRelatedPart({ displayName, value }) {
      if (Array.isArray(value) && value.length > 0) {
        const _renderContent = value.map((item, index) => {
          const approveNo = item.approveNo || '';

          return (
            <span>
              <a
                href="javascript:;"
                class="link-text"
                style="margin: 0"
                onClick={() => {
                  // this.$platform.openTab({
                  //   id: `M_VIP_SPAREPART_APPLY`,
                  //   title: '办理出入库',
                  //   close: true,
                  //   url: `/partV2/repertory/apply?noHistory=1&approveNo=${approveNo}&action=applyDetail`
                  // });
                  openAccurateTab({
                    type: PageRoutesTypeEnum.PageSparepartApply,
                    params: `noHistory=1&approveNo=${approveNo}&action=applyDetail`
                  })
                }}
              >
                {approveNo}
              </a>
              {index < value.length - 1 && ','}
            </span>
          );
        });

        return (
          <div class="form-view-row">
            <label>{displayName}</label>
            <div class="form-view-row-content">{_renderContent}</div>
          </div>
        );
      }

      return (
        <div class="form-view-row">
          <label>{displayName}</label>
        </div>
      );
    },

    openMap({ address, title }) {
      if (!address) return;
      this.$fast.map
        .display(address, { title })
        .catch(err => console.error('openMap catch an err: ', err));
    },

    openProduct(product) {
      if (!product.id) return;

      let fromId = window.frameElement?.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_view_${product.id}`,
      //   title: '产品详情',
      //   close: true,
      //   url: `/customer/product/view/${product.id}?noHistory=1`,
      //   fromId
      // });

      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: product.id,
        params: 'noHistory=1',
        fromId
      })
    },

    openCustomer(customer) {
      if (!customer.id) return;
      let fromId = window.frameElement?.getAttribute('id');
      // this.$platform.openTab({
      //   id: `customer_view_${customer.id}`,
      //   title: '客户信息',
      //   close: true,
      //   url: `/customer/view/${customer.id}?noHistory=1`,
      //   fromId
      // });

      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customer.id,
        params: 'noHistory=1',
        fromId
      })
    },

    mapFieldToDom(field, createElement) {
      const {
        formType,
        fieldName,
        displayName,
        isSystem,
        isHidden,
        isVisible
      } = field;
      if (formType === 'separator') {
        const cn = `iconfont icon-fdn-select ${!this.sectionState[field.id] &&
          'reversal'}`;
        return displayName ? (
          <h4 class="section-title">
            {displayName}
            <i class={cn} onClick={() => this.toggleDisplay(field.id)}></i>
          </h4>
        ) : null;
      }
      // 如果为隐藏的字段不显示
      if (isHidden == 1) return null;

      // 判断是否可见
      if (isVisible == false) return null;

      const originalObj = this.value;

      let params = {};
      // TODO ?
      // const value = isSystem
      //   ? originalObj[fieldName]
      //   : originalObj.attribute && originalObj.attribute[fieldName];
      const value = originalObj.attribute && originalObj.attribute[fieldName];

      params = { displayName, value, formType };

      if (this.$slots[fieldName]) {
        return this.$slots[fieldName];
      }

      // return slot
      if (this.$scopedSlots[fieldName]) {
        return this.$scopedSlots[fieldName]({
          displayName,
          value,
          formType,
          field
        });
      }

      // 加密字段
      if (value == '***') return this.buildCommonDom(params);

      // 电子签名、客户签名
      if (formType === 'autograph' || formType === 'systemAutograph') {
        params = {
          ...params,
          value
        };
        return this.buildAutoGraph(params);
      }

      // 组件默认视图
      const FormField = FieldManager.findField(field.formType);
      if (FormField && FormField.view) {
        const attrs = { props: { field, value } };
        return createElement(FormField.view, attrs);
      }

      if (formType === 'attachment' || formType === 'receiptAttachment') {
        params = {
          ...params,
          value: toArray(value).map(a => (
            <base-file-item file={a} readonly key={a.id} />
          ))
        };
      }

      if (formType === 'select' && field.setting.isMulti) {
        params = {
          ...params,
          value: toArray(value).join('，')
        };
      }

      if (formType === 'tags') {
        params = {
          ...params,
          value: toArray(value)
            .map(t => t.tagName)
            .join(' ')
        };
      }

      if (formType === 'select' && fieldName === 'tags') {
        params = {
          ...params,
          value: value.map(tag => tag.tagName).join('，')
        };
      }

      if (formType === 'user') {
        params = {
          ...params,
          value: this.formatValue(field, value)
        };
      }

      if (formType === 'user' && fieldName === 'manager') {
        params = {
          ...params,
          value: this.value.customerManagerName
        };
      }

      if (formType === 'linkman') {
        params = {
          ...params,
          value: value && value[0].label
        };
      }

      if (formType === 'customer') {
        params = {
          ...params,
          value: value
        };
        return this.buildCustomer(params);
      }

      if (formType === 'product') {
        params = {
          ...params,
          value: value
        };
        return this.buildProduct(params);
      }

      if (formType === 'address') {
        params = {
          ...params,
          value: fmt_address(value),
          originalVal: value
        };

        return this.buildAddressDom(params);
      }

      if (formType === 'phone' && fieldName === 'lmPhone') {
        params = {
          ...params,
          value
        };

        return this.buildPhoneDom(params);
      }

      if (formType == 'info') {
        params = {
          ...params,
          value: field.placeHolder
        };
        return this.buildInfoDom(params);
      }

      // 多行文本、客户关联字段、产品关联字段
      if (
        formType === 'textarea' ||
        formType === 'relationCustomer' ||
        formType === 'relationProduct'
      ) {
        params = {
          ...params,
          value
        };
        return this.buildTextarea(params);
      }

      if (formType === 'cascader') {
        params = {
          ...params,
          value: toArray(value).join('/')
        };
      }

      if (formType === 'timestamp') {
        params = {
          ...params,
          value: fmt_datetime(value)
        };
      }

      if (formType === 'related_task') {
        params = {
          ...params,
          value
        };
        return this.buildRelatedTask(params);
      }

      if (formType === 'relatedPart') {
        params = {
          ...params,
          value
        };
        return this.buildRelatedPart(params);
      }

      // other types: text date number datetime phone
      return this.buildCommonDom(params);
    },
    groupField(fields) {
      const newArr = [];
      let preIndex = 0;

      let allFields = this.allFields.length ? this.allFields : fields;

      fields
        // 隐藏不显示逻辑项
        .filter(
          item => !FormUtil.isHiddenField(item, this.value, allFields, false)
        )
        // 隐藏无内容的分割线
        .filter((field, index, arr) => {
          if (field.formType != 'separator') return true;

          const next = arr[index + 1];
          return null != next && next.formType != 'separator';
        })
        // 根据分割线分组
        .forEach((f, index, filterArr) => {
          if (f.formType === 'separator') {
            newArr.push(filterArr.slice(preIndex, index));
            preIndex = index;
          }

          if (index === filterArr.length - 1) {
            newArr.push(filterArr.slice(preIndex));
          }
        });

      return newArr;
    }
  },
  render(createElement) {
    // 去掉原先代码!Object.keys(this.value).length的判断
    // if (!this.fields.length || !Object.keys(this.value).length) return null;
    if (!this.fields.length) return null;
    const groups = this.groupField(this.fields);
    const domGroups = groups.map(group => {
      let currentGroupId = 0;

      const title = group
        .filter(f => f.formType === 'separator')
        .map(item => {
          currentGroupId = item.id;
          if (this.sectionState[currentGroupId] === undefined) {
            this.$set(this.sectionState, currentGroupId, true);
          }
          return this.mapFieldToDom(item, createElement);
        });

      const items = group
        .filter(f => f.formType !== 'separator')
        .map(item => this.mapFieldToDom(item, createElement));

      return (
        <div class="view-group">
          {title}
          <div class="items-of-group">
            {this.sectionState[currentGroupId] !== false && items}
          </div>
        </div>
      );
    });

    return <div class="form-view">{domGroups}</div>;
  }
};

export default FormView;
